package top.wshape1.shiziapi.project.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.wshape1.shiziapi.common.constant.BizCodeEnum;
import top.wshape1.shiziapi.common.domain.vo.PageVo;
import top.wshape1.shiziapi.common.exception.CustomException;
import top.wshape1.shiziapi.common.utils.R;
import top.wshape1.shiziapi.project.common.constant.DocumentConstant;
import top.wshape1.shiziapi.project.common.constant.EditConstant;
import top.wshape1.shiziapi.project.domain.EditHistory;
import top.wshape1.shiziapi.project.domain.vo.EditHistoryVo;
import top.wshape1.shiziapi.project.feign.UaaFeignService;
import top.wshape1.shiziapi.project.handler.LoginContextHandler;
import top.wshape1.shiziapi.project.mapper.EditHistoryMapper;
import top.wshape1.shiziapi.project.service.DocumentService;
import top.wshape1.shiziapi.project.service.EditHistoryService;
import top.wshape1.shiziapi.project.service.ProjectService;

import java.util.stream.Collectors;

/**
 * @author Wshape1
 * @description 针对表【t_project_edit_history】的数据库操作Service实现
 * @since 2024-12-24 23:20:52
 */
@Service
@RequiredArgsConstructor
public class EditHistoryServiceImpl extends ServiceImpl<EditHistoryMapper, EditHistory>
        implements EditHistoryService {

    private final ProjectService projectService;

    private final EditHistoryMapper editHistoryMapper;

    private final UaaFeignService uaaFeignService;

    private final DocumentService documentService;

    @Override
    public PageVo getHistoryList(Long projectId, Long page, Long limit) {

        if (!projectService.hasPermissionToEdit(projectId, LoginContextHandler.getUserId())) {
            throw new CustomException(R.instance(BizCodeEnum.PROJECT_PERMISSION_ERROR));
        }

        Page<EditHistory> historyPage = editHistoryMapper.selectPage(PageDTO.of(page, limit), new LambdaQueryWrapper<EditHistory>()
                .eq(EditHistory::getProjectId, projectId)
                .eq(EditHistory::getDeleted, 0)
                .orderByDesc(EditHistory::getUpdateTime));

        Page<EditHistoryVo> ret = new Page<>();

        BeanUtils.copyProperties(historyPage, ret, "records");

        if (!CollectionUtils.isEmpty(historyPage.getRecords())) {
            ret.setRecords(historyPage.getRecords().stream().map(editHistory -> {
                EditHistoryVo editHistoryVo = new EditHistoryVo();
                BeanUtils.copyProperties(editHistory, editHistoryVo);
                R<String> r = uaaFeignService.getUserNameById(editHistory.getEditorId());
                if (r.isSuccessful())
                    editHistoryVo.setEditorName(r.getData());
                editHistoryVo.setEditChange(this.getEditChange(editHistory));
                return editHistoryVo;
            }).collect(Collectors.toList()));
        }

        return new PageVo(ret);
    }

    private String getEditChange(EditHistory editHistory) {
        return switch (editHistory.getEditType()) {
            case EditConstant.EDIT_TYPE_MODIFY -> "修改了项目信息";
            case EditConstant.EDIT_TYPE_CREATE_DOC ->
                    "创建了" + DocumentConstant.typeIntToString(editHistory.getDocType()) + "文档：" +
                            this.parseObjectAndGet(editHistory.getEditAfter(), "name");
            case EditConstant.EDIT_TYPE_DELETE_DOC ->
                    "删除了" + DocumentConstant.typeIntToString(editHistory.getDocType()) + "文档：" +
                            this.parseObjectAndGet(editHistory.getEditBefore(), "name");
            case EditConstant.EDIT_TYPE_RENAME_DOC ->
                    "重命名了" + DocumentConstant.typeIntToString(editHistory.getDocType()) + "文档：" +
                            editHistory.getEditBefore() + " -> " + editHistory.getEditAfter();
            case EditConstant.EDIT_TYPE_SAVE_VERSION ->
                    "保存了" + DocumentConstant.typeIntToString(editHistory.getDocType()) + "文档版本：" +
                            this.parseObjectAndGet(editHistory.getEditAfter(), "version");
            case EditConstant.EDIT_TYPE_DELETE_VERSION ->
                    "删除了" + DocumentConstant.typeIntToString(editHistory.getDocType()) + "文档版本：" +
                            this.parseObjectAndGet(editHistory.getEditBefore(), "version");
            default -> null;
        };
    }

    private String parseObjectAndGet(String mapStr, String key) {
        JSONObject jsonObject = JSON.parseObject(mapStr);
        if (jsonObject == null)
            return null;
        return jsonObject.getString(key);
    }

}




